package petrochina.company.electric.ui.dialog;

import android.content.Context;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.toast.ToastUtils;
import com.tencent.mmkv.MMKV;
import com.ut.ble.BleDevice;
import com.ut.ble.scan.IScanCallback;
import com.ut.blelock.BleLockController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import petrochina.company.electric.R;
import petrochina.company.electric.aop.SingleClick;
import petrochina.company.electric.app.AppAdapter;
import petrochina.company.electric.http.api.BleDeviceListApi;
import petrochina.company.electric.http.api.TaskDetailStepApi;

/**
 * 优特蓝牙锁搜索 连接 操作
 */
public final class BleLockSearchMenuDialog {

    public static final class Builder
            extends BaseDialog.Builder<Builder>
            implements BaseAdapter.OnChildClickListener,
            View.OnLayoutChangeListener, Runnable {

        @SuppressWarnings("rawtypes")
        @Nullable
        private OnListener mListener;
        private boolean mAutoDismiss = true;

        private final RecyclerView mRecyclerView;
        private final AppCompatImageView mCancelView;
        private final AppCompatButton mSearchView;

        private final BleLockAdapter mAdapter;

        private final String LOCK_SDK_KEY = "6E45B3E24DEE8603";

        public Builder(Context context) {
            super(context);
            setContentView(R.layout.ble_search_dialog);
            setAnimStyle(BaseDialog.ANIM_BOTTOM);
            setHeight(getResources().getDisplayMetrics().heightPixels * 2 / 3);
            mRecyclerView = findViewById(R.id.rv_ble_list);
            mCancelView = findViewById(R.id.iv_ble_search_closer);
            mSearchView = findViewById(R.id.btn_dialog_search);
            setOnClickListener(mCancelView, mSearchView);

            mAdapter = new BleLockAdapter(getContext());
            mAdapter.setOnChildClickListener(R.id.btn_connect_state, this);
            mRecyclerView.setAdapter(mAdapter);
            initData();
        }

        private void initData() {
            BleLockController.getInstance().init(getContext(), LOCK_SDK_KEY);
        }

        protected void scanBleDevice() {
            //查找蓝牙设备
            BleLockController.getInstance().scan(new IScanCallback() {
                @Override
                public void onDeviceFound(BleDevice bleDevice, List<BleDevice> result) {
                    if (mAdapter.getCount() != result.size()) {
                        mAdapter.clearData();

                        List<BleDeviceListApi.Bean> list = new ArrayList<>();

                        for (BleDevice device : result) {
                            BleDeviceListApi.Bean bean = verifyAndGetDevice(device.getName(), device.getDeviceUUID());
                            if (bean != null){
                                bean.setDevice(device);
                                list.add(bean);
                            }
                        }
                        if (list.size()>0){
                            mAdapter.setData(list);
                        }
                    }
                }

                @Override
                public void onScanFinish(List<BleDevice> result) {
                    System.out.println("--------- onScanFinish " + result.toString());
                }

                @Override
                public void onScanTimeout() {
                    System.out.println("--------- onScanTimeout ");
                }
            });
        }

        /**
         * 根据equipType校验设备并返回实例4：蓝牙锁
         */
        private BleDeviceListApi.Bean verifyAndGetDevice(String name, String address) {
            if (TextUtils.isEmpty(name) || "NULL".equals(name)) {
                return null;
            }
            MMKV mmkv = MMKV.defaultMMKV();
            Gson gson = new Gson();
            List<BleDeviceListApi.Bean> devicesList = null;
            String listJson = mmkv.getString("bleDevices4Json", null);
            if (TextUtils.isEmpty(listJson)) {
                return null;
            }
            devicesList = gson.fromJson(listJson, new TypeToken<List<BleDeviceListApi.Bean>>() {
            }.getType());
            if (devicesList == null || devicesList.size() == 0) {
                return null;
            }
            BleDeviceListApi.Bean bean = new BleDeviceListApi.Bean();
            bean.setBluetookthAddress(address);
            // 判断该设备是否存在于设备列表中
            if (!devicesList.contains(bean)) {
                return null;
            } else {
                return devicesList.get(devicesList.indexOf(bean));
            }
        }

        protected void stopScanBleDevice() {
            //停止查找蓝牙设备
            BleLockController.getInstance().stopScan();
        }

        @Override
        public Builder setGravity(int gravity) {
            switch (gravity) {
                // 如果这个是在中间显示的
                case Gravity.CENTER:
                case Gravity.CENTER_VERTICAL:
                    // 不显示取消按钮
                    setCancel(null);
                    // 重新设置动画
                    setAnimStyle(BaseDialog.ANIM_SCALE);
                    break;
                default:
                    break;
            }
            return super.setGravity(gravity);
        }

        @Override
        public Builder addOnDismissListener(@NonNull BaseDialog.OnDismissListener listener) {
            return super.addOnDismissListener(listener);
        }

        public Builder setList(int... ids) {
            List<String> data = new ArrayList<>(ids.length);
            for (int id : ids) {
                data.add(getString(id));
            }
            return setList(data);
        }

        public Builder setList(String... data) {
            return setList(Arrays.asList(data));
        }

        @SuppressWarnings("all")
        public Builder setList(List data) {
            mAdapter.setData(data);
            mRecyclerView.addOnLayoutChangeListener(this);
            return this;
        }

        public Builder setCancel(@StringRes int id) {
            return setCancel(getString(id));
        }

        public Builder setCancel(CharSequence text) {
            //隐藏
//            mCancelView.setText(text);
            return this;
        }

        public Builder setAutoDismiss(boolean dismiss) {
            mAutoDismiss = dismiss;
            return this;
        }

        @SuppressWarnings("rawtypes")
        public Builder setListener(OnListener listener) {
            mListener = listener;
            return this;
        }

        @SingleClick
        @Override
        public void onClick(View view) {
            if (mAutoDismiss) {
                dismiss();
            }

            if (view == mCancelView) {
                if (mListener == null) {
                    return;
                }
                mListener.onCancel(getDialog());
            }
            if (view == mSearchView) {
                scanBleDevice();
//                stopScanBleDevice();

            }

        }

        /**
         * {@link View.OnLayoutChangeListener}
         */
        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
            mRecyclerView.removeOnLayoutChangeListener(this);
            // 这里一定要加延迟，如果不加在 Android 9.0 上面会导致 setLayoutParams 无效
            post(this);
        }

        @Override
        public void run() {
            final ViewGroup.LayoutParams params = mRecyclerView.getLayoutParams();
            final int maxHeight = getScreenHeight() / 4 * 3;
            if (mRecyclerView.getHeight() > maxHeight) {
                if (params.height != maxHeight) {
                    params.height = maxHeight;
                    mRecyclerView.setLayoutParams(params);
                }
                return;
            }

            if (params.height != ViewGroup.LayoutParams.WRAP_CONTENT) {
                params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                mRecyclerView.setLayoutParams(params);
            }
        }

        /**
         * 获取屏幕的高度
         */
        private int getScreenHeight() {
            Resources resources = getResources();
            DisplayMetrics outMetrics = resources.getDisplayMetrics();
            return outMetrics.heightPixels;
        }

        @Override
        public void onChildClick(RecyclerView recyclerView, View childView, int position) {
            if (mAutoDismiss) {
                dismiss();
            }
            if (mListener == null) {
                return;
            }
            mListener.onSelected(getDialog(), position, mAdapter.getItem(position));
            stopScanBleDevice();
        }
    }

    private static final class BleLockAdapter extends AppAdapter<BleDeviceListApi.Bean> {

        private BleLockAdapter(Context context) {
            super(context);
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ViewHolder();
        }

        private final class ViewHolder extends AppAdapter<?>.ViewHolder {

            private final TextView tvDeviceName;
            private final TextView tvMac;

            private final AppCompatButton btnConnectState;

            ViewHolder() {
                super(R.layout.ble_search_item);
                tvDeviceName = findViewById(R.id.tv_device_name);
                tvMac = findViewById(R.id.tv_mac);
                btnConnectState = findViewById(R.id.btn_connect_state);
            }

            @Override
            public void onBindView(int position) {
                tvDeviceName.setText(getItem(position).getName());
                tvMac.setText("编号：" + getItem(position).getCode());
            }
        }
    }

    public interface OnListener<T> {

        /**
         * 选择条目时回调
         */
        void onSelected(BaseDialog dialog, int position, T t);

        /**
         * 点击取消时回调
         */
        default void onCancel(BaseDialog dialog) {
        }
    }
}